package com.apestech.framework.dictionary;

import com.apestech.framework.db.SqlResultSet;
import com.apestech.framework.db.SqlSession;
import com.apestech.framework.db.callback.QueryCallBackHandler;
import com.apestech.framework.dictionary.modul.Table;
import com.apestech.framework.json.JSON;
import com.apestech.framework.json.JSONArray;
import com.apestech.framework.json.JSONObject;
import com.apestech.framework.metadata.MetaData;
import com.apestech.framework.util.StringUtil;

import java.util.ArrayList;

public class DataTableCache extends StringUtil{

    private QueryCallBackHandler queryCallBackHandler;
    private MetaData md;
    private Table datatab;
    private String tabname;
    private SqlSession session;
    private String col="";
    private String remarks="";
    private String dateCol="";
    private String numCol="";
    private String intCol="";
    private int inx=0;

    public DataTableCache(SqlSession session, MetaData md, String tabname){
        queryCallBackHandler= new QueryCallBackHandler() {
            @Override
            public void getData(SqlResultSet rs, JSONArray rslist) throws Exception {
                writeTable(rs);
            }
        };
        this.md=md;
        this.session=session;
        this.tabname=tabname;
    }

    public QueryCallBackHandler getQueryCallBackHandler() {
        return queryCallBackHandler;
    }

    public DataTableCache(SqlSession session, String tabname){
        this.tabname=tabname;
        this.session=session;
    }

    private void writeTable(SqlResultSet rs) throws Exception {
        while (rs.next()){
            if(datatab==null){
                datatab=new Table(tabname);
            }
            String TABLE_NAME="";
            JSONObject m=rs.toRowJson();
            String NAME=m.getString("COLUMN_NAME");
            JSONObject map=DictUtil.getReslutData(NAME, m.getString("REMARKS"), m.getString("TYPE_NAME"),
                    m.getString("COLUMN_DEF"), m.getString("NULLABLE"),
                    m.get("CHAR_OCTET_LENGTH"), m.get("COLUMN_SIZE"),
                    m.get("DECIMAL_DIGITS"));

            String tab=rs.getString("TABLE_NAME");
            if(!TABLE_NAME.equals(tab)){
                JSONObject key=md.getTableKey(tab);
                if(key.size()>0){
                    JSONObject pkey=new JSONObject();
                    pkey.put("PRIMARY", key);
                    datatab.setPkKeyfromJSON(key);
                }
                JSONObject fkey=md.getImportedKey(tab);
                if(fkey.size()>0){
                    datatab.setPkFKeyFromJSON(tab, fkey);
                }
            }
            map.put("TABLE_NAME", tab);
            writeCol(datatab.addField(map));
        }
//        String value="";
//        if(datatab!=null){
//            value=JSON.toJSONString(datatab);
//        }
        session.saveTabCache(tabname, JSON.toJSONByte(datatab));
    }

    private void writeCol(String COLUMN_NAME) throws Exception {
        if((","+col+",").indexOf(","+COLUMN_NAME+",")>=0) return;
        String REMARKS=datatab.getRemarks(COLUMN_NAME);
        REMARKS=formatIdMemo(REMARKS);
        if("".equals(REMARKS) || REMARKS==null){
            REMARKS=COLUMN_NAME;
        }
        if(REMARKS==null){
            REMARKS="";
        }
        if(REMARKS.indexOf("(")>=0 && REMARKS.indexOf(":")>=0 && REMARKS.indexOf(")")>=0){  //存在数据列表情况
            String memo=getSplitList(REMARKS);
            REMARKS=getSpiltId(REMARKS);
            ArrayList<ArrayList<String>> list=getStrSplitList("; :", memo);
            int len=list.size();
            for(int i=0; i<len; i++){
                String sid=list.get(i).get(0);
                try{
                    String stext=list.get(i).get(1);
                    datatab.addList(COLUMN_NAME, sid, stext);
                } catch (Exception e){
                    throw new Exception("请检查字段["+COLUMN_NAME+"]备注里的配置\r\n["+memo+"]中\r\n["+sid+"]部分是否正确！");
                }

            }
        }
        datatab.setRemarks(COLUMN_NAME, REMARKS);
        if(!"".equals(col)){
            col=col+",";
        }
        col=col+COLUMN_NAME;
        if(!"".equals(remarks)){
            remarks=remarks+",";
        }
        remarks=remarks+REMARKS;

        String typeName=datatab.getTypeName(COLUMN_NAME);
        if(typeName.indexOf("DATE")>=0 || typeName.indexOf("TIME")>=0){
            if(!"".equals(dateCol)){
                dateCol=dateCol+",";
            }
            dateCol=dateCol+COLUMN_NAME;
        } else if(typeName.indexOf("NUMBER")>=0){
            if(datatab.getSize(COLUMN_NAME)>0){
                if(!"".equals(numCol)){
                    numCol=numCol+",";
                }
                numCol=numCol+COLUMN_NAME;
            } else {
                if(!"".equals(intCol)){
                    intCol=intCol+",";
                }
                intCol=intCol+COLUMN_NAME;
            }
        }

        inx++;
        datatab.setColumn(col);
        datatab.setDateColumn(dateCol);
        datatab.setNumColumn(numCol);
        datatab.setIntColumn(intCol);
        datatab.setRemarks(remarks);
    }

    public Table getTab(){
        return datatab;
    }

}
